<?php
/**
 * Created by PhpStorm.
 * User: caoyangmin
 * Date: 16/11/16
 * Time: 上午12:14
 */

namespace Once\Orm;


/**
 * Class Builder
 * @package Once\Orm
 */
class Builder extends \Illuminate\Database\Eloquent\Builder
{
    /**
     * 创建models时初始化entity信息
     * @param array $columns
     * @return mixed
     */
    public function getModels($columns = ['*'])
    {
        $results = $this->query->get($columns);//->all(); TODO 兼容lumen 5.*各版本
        $connection = $this->model->getConnectionName();

        $instance = new Model();

        $instance->setTable($this->model->getTable());
        $instance->fillable($this->model->getFillable());
        $instance->setEntityContainer($this->model->getEntityContainer());

        $instance->setConnection($connection);
        $items = array_map(function ($item) use ($instance) {
            return $instance->newFromBuilder($item);
        }, $results);

        return $instance->newCollection($items)->all();
    }

    /**
     * 返回实体
     * @return mixed
     */
    public function entity(){
        $data = $this->get()->first();
        if($data==null){
            return null;
        }
        return $this->model->getEntityContainer()->make(app(), $data->getAttributes());
    }

    /**
     * 返回实体
     * @return mixed
     */
    public function entities(){
        $datas = [];
        foreach ($this->get() as $data){
            $datas[] = $this->model->getEntityContainer()->make(app(), $data->getAttributes());
        }
        return $datas;
    }

}